﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Peak.ApplicationServices;
using Peak.ApplicationServices.Services;
using Peak.Core;
using Peak.Core.DataInterfaces;
using Peak.Resources;
using Peak.Web.Controllers.Models;
using Peak.Web.Controllers.Services;
using SharpArch.Web.NHibernate;
using MvcContrib;
using Peak.ApplicationServices.CsvWritter;
using System.IO;

namespace Peak.Web.Controllers
{
  public class ProjectBacklogController : BaseController
  {
    private readonly IStoryService _storyService;
    private readonly IPriorityUpdater _priorityUpdater;

    public ProjectBacklogController(ISessionService sessionService, IStoryService storyService, IPriorityUpdater priorityUpdater)
      :base(sessionService)
    {
      _storyService = storyService;
      _priorityUpdater = priorityUpdater;
    }

    public ActionResult Index(StoryFilterModel filter)
    {
      StoryFilter sf = new StoryFilter();
      filter.Update(sf,_sessionService.Project.Id);
      Page<Story> page = _storyService.GetPage(sf);

      BacklogModel pbm = new BacklogModel() { Stories = page.Results.Select(f=>new StoryModel(f)).ToList(), Filter = filter };
      
      if (!Request.IsAjaxRequest())
      {
        _sessionService.BackLink.Reset();
        return View(pbm);
      }
      else
      {        
        return View("Table",pbm);
      }
    }              

    [Transaction]
    public ActionResult Remove(int[] ids)
    {
      Project project = _sessionService.Project;
      foreach (int id in ids)
      {
        Story s = _storyService.Get(id);
        project.RemoveStory(s);
        _storyService.Delete(s);        
      }
      return this.RedirectToAction(f=>f.Index(null));
    } 

    [Transaction]
    public ActionResult Move(StoryFilterModel filter, int id, int newIndex)
    {
      StoryFilter sf = new StoryFilter();
      filter.Update(sf, _sessionService.Project.Id);
      Page<Story> stories = _storyService.GetPage(sf);
      return this.Content(_priorityUpdater.Move(sf, stories, id, newIndex).Priority.ToString());      
    }

    [Transaction]
    public ActionResult AddToCurrentSprint(int[] ids)
    {
      if(ids == null && ids.Length == 0)
      {
        return MessageBox(Messages.InvalidOperation);
      }
      foreach (int id in ids)
      {
        Story story = _storyService.Get(id);
        _sessionService.Project.CurrentSprint.AddStory(story);
      }
      return this.RedirectToAction(f => f.Index(null));
    }

    public ActionResult Export(int[] ids)
    {
      List<Story> list = new List<Story>();
      foreach (int id in ids)
      {
        Story s = _storyService.Get(id);
        list.Add(s);        
      }
      MemoryStream ms = new MemoryStream();
      StreamWriter streamWriter = new StreamWriter(ms,Encoding.UTF8);      
      StoriesCSVWriter writer = new StoriesCSVWriter();
      writer.Write(list,streamWriter);
      streamWriter.Flush();
      ms.Position = 0;

      FileStreamResult fileStream = new FileStreamResult(ms, "application/csv");
      fileStream.FileDownloadName = "StoriesExport"+DateTime.Now.ToString()+".csv";
      return fileStream;
    }

    //public ActionResult ManagePriorities(StoryFilterModel filter)
    //{
    //  if (filter.ManagePriorities)
    //  {
    //    filter.SortDirection = SortDirection.Desc;
    //    filter.SortOrder = StorySortOrder.Priority;
    //  }

    //  return this.RedirectToAction(f => f.Index(null));
    //} 

    //[Transaction]
    //public ActionResult UpdatePosition(StoryFilterModel filter, int id, int newPosition)
    //{
    //  StoryFilter f = StoryFilterModelTranslator.CreateFilter(filter);      
    //  Story s = _priorityUpdater.Move(f, _storyService.GetPage(f), id, newPosition);

    //  return View("Item", new StoryModel(s, filter.ManagePriorities));      
    //}

    /*

    public ActionResult Summary(StoryFilterModel filter, int id)
    {
      return View("Item", new StoryModel(_storyService.Get(id), filter.ManagePriorities));
    }    

    public ActionResult Edit(int id)
    {
      Story s = _storyService.Get(id);
      StoryModel sm = new StoryModel(s, false);
      return View("Edit", sm);
    }

    [Transaction]    
    public ActionResult Update(StoryFilterModel filter, int storyId)
    {
      Story story = _storyService.Get(storyId);      
      Check.Require(story != null);
      TryUpdateModel(story);

      if(!story.IsValid())
      {
        _storyService.DbContext.RollbackTransaction();
        return View("Edit", new StoryModel(story, false));
      }
      return View("Item",new StoryModel(story,filter.ManagePriorities));
    }

    public ActionResult New(StoryFilterModel filter)
    {
      return View(new StoryModel(new Story(), filter.ManagePriorities));
    }

    [Transaction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult New(StoryFilterModel filter, Story story)
    {
      if (!story.IsValid())
      {
        return View(new StoryModel(story, false));
      }
      _projectRepository.Get(Storage.Current.ProjectId.Value).AddSprintStory(story);      
      return View("ItemAndNew", new StoryModel(story, filter.ManagePriorities));
    }    
    */
  }
}